﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Web.Script.Serialization;
using System.Xml.Linq;

namespace Twi.COMMON.Core
{
    /*
    * Copyright: ©2010-2013 Twilight软件开发工作室版权所有
     * Author:xuzhihong
     * Description:统一返回类型(属性都小写是为了序列化后到js中都是小写的)
     * 改进了DataTable，IList、List等单独序列化的问题
     * 整合全服务器端权限验证
     * 整合了Session过期重新登录问题
     * 2013-08-14：增加了Excute方法来简化Twi.Pages的代码编写量
     * 2015-04-27：增加了ToXElement方法来兼容xml结构数据
     */
    public class TwiReturn
    {
        public TwiReturn()
        {
            this.hasRight = false;
            this.success = false;
            this.knowError = TwiKnowErrors.Unkown;
            this.IsNeedCheckRight = true;
            this.list = new List<string>();
        }
        /// <summary>
        /// 返回id
        /// </summary>
        public object id
        {
            get;
            set;
        }

        /// <summary>
        /// 编号，一般用来存储success=true的特殊自定义标识代码
        /// 【如果此刻需要额外附加说明信息，可存在errors字段中】
        /// 仅success=true时: code + errors 结合使用
        /// </summary>
        public string code
        {
            get;
            set;
        }

        /// <summary>
        /// 操作是否顺利完成
        /// </summary>
        public bool success
        {
            get;
            set;
        }
        /// <summary>
        /// 是否有权限进行相应操作
        /// </summary>
        public bool hasRight
        {
            get;
            set;
        }
        /// <summary>
        /// 操作权限名称
        /// </summary>
        public string rightName
        {
            get;
            set;
        }
        /// <summary>
        /// 已知错误
        /// </summary>
        public TwiKnowErrors knowError
        {
            get;
            set;
        } 
        /// <summary>
        /// 错误
        /// </summary>
        public string errors
        {
            get;
            set;
        }
        /// <summary>
        /// 消息
        /// </summary>
        public string message
        {
            get
            {
                string msg = string.Empty;
                if (!this.success)
                {
                    if (this.knowError == TwiKnowErrors.SessionExpired)
                    {
                        msg = string.Format("系统发生异常：{0}", TwiKnowErrorMsg.dictErrors[this.knowError]);
                    } 
                    else
                    {
                        if (this.hasRight)
                        {
                            if (this.knowError != TwiKnowErrors.Unkown)
                            {
                                msg = string.Format("系统发生异常：{0}", TwiKnowErrorMsg.dictErrors[this.knowError]);
                            }
                            else
                            {
                                msg = string.Format("系统发生异常：{0}", this.errors);
                            }
                        }
                        else
                        {
                            this.knowError = TwiKnowErrors.HasNoRight;
                            msg = string.Format("您没有操作权限，权限名称为：{0}", this.rightName);
                        }
                    }
                }
                else
                {
                    msg = string.Format("操作成功!");
                }
                return msg;
            }
        }

        /// <summary>
        /// 返回数据(序列化数据)
        /// </summary>
        public object data
        {
            get;
            set;
        }

        private int _totalCount = 0;
        /// <summary>
        /// 总记录数,默认取tSoucre.Count()
        /// </summary>
        public int totalCount
        {
            get
            {
                if (_totalCount == 0)
                {
                    var source = data as IEnumerable<object>;
                    if (source !=null)
                    {
                        _totalCount = source.Count();
                    }                    
                }
                return _totalCount;
            }
            set
            {
                _totalCount = value;
            }
        }

        /// <summary>
        /// 主要是为了扩展AuthorityList
        /// </summary>
        public List<string> list
        {
            get;
            set;
        }

        /// <summary>
        /// 是否需要权限检查
        /// </summary>
        /// <remarks>JSON.NET 需要使用JsonIgnore属性才能忽略序列化，但是目前未直接引用JSON.NET</remarks>
        [ScriptIgnore]
        public bool IsNeedCheckRight
        {
            get;
            set;
        }

        /// <summary>
        /// Twi.Pages统一执行方法
        /// </summary>
        /// <param name="twi"></param>
        /// <param name="action"></param>
        public static void Execute(ref TwiReturn twi,Action action)
        {
            twi.hasRight = true;
            try
            {
                if (twi.IsNeedCheckRight)
                {
                    UserContext.CheckRight(ref twi);
                }
                else
                {
                    twi.hasRight = true;
                }
                action();
                twi.success = true;
            }
            catch (System.Exception ex)
            {
                twi.errors = ex.Message;
            }
        }

        /// <summary>
        /// Twi.Pages统一执行方法,返回TwiReturn
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public static TwiReturn Execute(Action action)
        {
            TwiReturn twi = new TwiReturn();
            twi.hasRight = true;
            try
            {
                if (twi.IsNeedCheckRight)
                {
                    UserContext.CheckRight(ref twi);
                }
                else
                {
                    twi.hasRight = true;
                }
                action();
                twi.success = true;
            }
            catch (System.Exception ex)
            {
                twi.errors = ex.Message;
            }
            return twi;
        }

        /// <summary>
        /// 复制对象
        /// </summary>
        /// <param name="twiOld"></param>
        /// <returns></returns>
        public static TwiReturn Clone(TwiReturn twiOld)
        {
            TwiReturn twi = new TwiReturn();
            twi.success = twiOld.success;
            twi.errors = twiOld.errors;
            twi.data =  twiOld.data;
            twi.id = twiOld.id;
            twi.hasRight = twiOld.hasRight;
            twi.rightName = twiOld.rightName;
            twi.totalCount = twiOld.totalCount;
            twi.knowError = twiOld.knowError;
            twi.list = twi.list;
            return twi;
        }

        /// <summary>
        /// 将TwiReturn对象转化为XElement对象
        /// </summary>
        /// <param name="twi"></param>
        /// <returns></returns>
        public static XElement ToXElement(TwiReturn twi) 
        {
            XElement xelReturn = new XElement("TwiReturn");
            xelReturn.Add(
                new XElement("success", twi.success),
                new XElement("errors", twi.errors),
                new XElement("id", twi.id),
                new XElement("hasRight", twi.hasRight),
                new XElement("rightName", twi.rightName),
                new XElement("totalCount", twi.totalCount),
                new XElement("knowError", twi.knowError.ToString())
                );
            XElement xelData = twi.data as XElement;
            if (xelData != null) {
                if (xelData.HasElements)
                {
                    xelReturn.Add(new XElement("data", xelData.Nodes()));
                }
                else {
                    xelReturn.Add(new XElement("data", xelData));
                }                
            }
            else{
                xelReturn.Add(new XElement("data", "" + twi.data));
            }

            XElement xelList = new XElement("list");
            if (twi.list != null && twi.list.Count > 0)
            {
                for (var i = 0; i < twi.list.Count; i++)
                {
                    xelList.Add(new XElement("item",twi.list[i]));
                }
            }
            xelReturn.Add(xelList);
            return xelReturn;
        }
    }

    /// <summary>
    /// 已知错误提示信息
    /// </summary>
    public class TwiKnowErrorMsg
    {
        private TwiKnowErrorMsg() { }
        public static Dictionary<TwiKnowErrors, string> dictErrors
        {
            get
            {
                Dictionary<TwiKnowErrors, string> dicts = new Dictionary<TwiKnowErrors, string>();
                dicts.Add(TwiKnowErrors.HasNoRight,"您没有权限进行此操作");
                dicts.Add(TwiKnowErrors.SessionExpired, "由于长时间未操作，会话已经过期，需要重新登录！");
                return dicts;
            }
        }
    }

    /// <summary>
    /// 已知错误
    /// </summary>
    public enum TwiKnowErrors
    {
        /// <summary>
        /// defaults,未知
        /// </summary>
        Unkown = 100,
        /// <summary>
        /// 无权限操作
        /// </summary>
        HasNoRight,  
        /// <summary>
        /// 会话过期
        /// </summary>
        SessionExpired
    }

}
